package com.erpanderp.wam.adm.view;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.el.MethodExpression;
import javax.faces.event.ActionListener;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIParameter;
import javax.faces.component.behavior.ClientBehaviorContext.Parameter;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.MethodExpressionActionListener;
import javax.servlet.http.HttpSession;

import org.primefaces.component.menubar.Menubar;
import org.primefaces.component.menubutton.MenuButton;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.component.submenu.Submenu;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;

import com.erpanderp.wam.adm.model.entity.Module;
import com.erpanderp.wam.adm.model.entity.Service;
import com.erpanderp.wam.adm.model.entity.ServiceGroup;
import com.erpanderp.wam.adm.model.service.RoleServiceDAO;
import com.erpanderp.wam.adm.model.service.RoleServicegroupDAO;
import com.erpanderp.wam.adm.model.service.WAMUserModuleEngine;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.util.CommonLookup;
import com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.Param;

@ManagedBean
@SessionScoped
public class UserMenuBean implements Serializable {

	private static final long serialVersionUID = 1L;
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
			.getExternalContext().getSession(true);
	private WAMUser wamUser;
	WAMUserModuleEngine wamUserModuleEngine = new WAMUserModuleEngine();
	private String selectedModule;
	private MenuButton moduleMenuButton = new MenuButton();
	private Menubar menubar = new Menubar();

	RoleServicegroupDAO roleServicegroupDAO = new RoleServicegroupDAO();
	RoleServiceDAO roleServiceDAO = new RoleServiceDAO();
	
	public UserMenuBean() {

		wamUser = (WAMUser) session
				.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
		if (wamUser != null) {
			System.out.println("Login Employee: " + wamUser.getEmployeeCode());
			
				List<Module> modules = new ArrayList<Module>();
				modules = wamUserModuleEngine.getUserModules(wamUser
						.getEmployeeCode());
				Collections.sort(modules);
				System.out.println("MODULES FROM DB="+modules.size());
				if (modules != null && modules.size() > 0) {
					setSelectedModule(modules.get(0).getModuleName());
					System.out.println(modules != null ? modules.size() : 0);
					for (Module module : modules) {
						System.out.println("Module Name: " + module.getModuleName());
						MenuItem item = new MenuItem();
						item.setValue(module.getModuleName());
						item.setId("_MODULEMENUITEM_"
								+ module.getModuleId());
						item.addActionListener(createActionListener("#{userMenuBean.moduleMenuAction}"));
						item.setAjax(false);
						item.setUpdate("@form");
						moduleMenuButton.getChildren().add(item);
					}
					generateMenu(modules.get(0).getModuleId());
					FacesContext context = FacesContext.getCurrentInstance();
					context.getApplication().getNavigationHandler().handleNavigation(context, null, "wudashboard");
					
				}
			
		}
	}

	private void goToModuleHome(){
		FacesContext context = FacesContext.getCurrentInstance();
		if(getSelectedModule() != null){
			if(getSelectedModule().equals(CommonLookup.MODULENAME_ADMINISTRATION)){
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "administration");		
			}	
			if(getSelectedModule().equals(CommonLookup.MODULENAME_TIME_MANAGEMENT)){
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "timemanagement");		
			}	
			if(getSelectedModule().equals(CommonLookup.MODULENAME_PERSONAL_SKILLS)){
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "personalskills");		
			}	
			if(getSelectedModule().equals(CommonLookup.MODULENAME_TRAVEL_MANAGEMENT)){
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "travelmanagement");		
			}	
			if(getSelectedModule().equals(CommonLookup.MODULENAME_CLAIMS)){
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "claims");		
			}	
			if(getSelectedModule().equals(CommonLookup.MODULENAME_ERECRUITMENT)){
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "erecruitment");		
			}	
		}
 			
	}
	
	public void moduleMenuAction(ActionEvent e) {
		Long moduleId = Long.parseLong(e.getComponent().getId()
				.substring(e.getComponent().getId().length() - 1));
		System.out.println("MODULEID: " + moduleId);
		generateMenu(moduleId);
		setSelectedModule(((MenuItem)e.getComponent()).getValue().toString());
		goToModuleHome();
	}

	public void redirectFromDashboard(){
		
	} 
	
	public void generateMenu(Long moduleId) {
		menubar.getChildren().clear();
		List<ServiceGroup> serviceGroups = roleServicegroupDAO
				.getRoleServicegroups(wamUser.getEmployee().getEmployeeId(),
						moduleId);
		for (ServiceGroup serviceGroup : serviceGroups) {
			System.out.println(serviceGroup.getServicegroupName());
			Submenu submenu = new Submenu();
			submenu.setLabel(serviceGroup.getDisplayName());
			// submenu.setId(serviceGroup.getServicegroupName() + "_SUBMENU");

			for (Service service : serviceGroup.getServices()) {
				MenuItem item = new MenuItem();
				item.setValue(service.getDisplayName());
				// item.setId(service.getServiceName() + "_MENUITEM");
				item.setActionExpression(createAction("#{userMenuBean.navigate}", String.class));
				UIParameter param = new UIParameter();
				param.setName("outcome");
				param.setValue(service.getStartPage());
				item.getChildren().add(param);
				submenu.getChildren().add(item);
			}

			menubar.getChildren().add(submenu);
		}
		List<Service> services = roleServiceDAO.getRoleServices(wamUser.getEmployee().getEmployeeId(),moduleId );
		
		for (Service service : services) {
			MenuItem item = new MenuItem();
			item.setValue(service.getDisplayName());
			// item.setId(service.getServiceName() + "_MENUITEM");
			item.setActionExpression(createAction("#{userMenuBean.navigate}", String.class));
			UIParameter param = new UIParameter();
			param.setName("outcome");
			param.setValue(service.getStartPage());
			item.getChildren().add(param);
			menubar.getChildren().add(item);
		}
		
		
	}

	public String navigate(){
		Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String outcome = null;
		if(params != null && params.size() > 0){
			System.out.println(params.size());
			outcome = params.get("outcome");
			System.out.println(outcome);	
		}
		return outcome;
	}

	public static MethodExpressionActionListener createActionListener(
			String actionListenerExpression) {
		FacesContext context = FacesContext.getCurrentInstance();
		return new MethodExpressionActionListener(context
				.getApplication()
				.getExpressionFactory()
				.createMethodExpression(context.getELContext(),
						actionListenerExpression, null,
						new Class[] { ActionEvent.class }));
	}

	public static MethodExpression createAction(String actionExpression, Class<?> returnType) {
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getApplication().getExpressionFactory().createMethodExpression(context.getELContext(), actionExpression, returnType, new Class[0]);
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public String getSelectedModule() {
		return selectedModule;
	}

	public void setSelectedModule(String selectedModule) {
		this.selectedModule = selectedModule;
	}

	public MenuButton getModuleMenuButton() {
		return moduleMenuButton;
	}

	public void setModuleMenuButton(MenuButton moduleMenuButton) {
		this.moduleMenuButton = moduleMenuButton;
	}	

	public Menubar getMenubar() {
		return menubar;
	}

	public void setMenubar(Menubar menubar) {
		this.menubar = menubar;
	}



}
